package com.dfiov.cloud.msmtools.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author zl
 * @since 2020/1/2
 */
@Slf4j
public class ExcelUtils {
    private final static String DEFAULT_NAME = "Sheet1";

    private ExcelUtils() {

    }

    /**
     * @param tableName 文件名称
     * @param data      导出的数据
     * @param tClass    数据对应实体类的class
     * @param response  响应数据承载体
     */
    public static <T> void export(String tableName,String sheetName, List<T> data, Class<T> tClass, HttpServletResponse response) {
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            String fileName = String.format("%s.xlsx", tableName);
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            EasyExcel.write(outputStream, tClass)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .sheet(sheetName)
                    .doWrite(() -> data);
        } catch (Exception e) {
            log.error("{}导出异常", tableName, e);
        }
    }


}

